# -*-coding: utf-8 -*-
# by zw on 2018/2/24


import logging

from sanic import response
from utils.mongo import get_app_config_collection
from utils.util import _render_template, merge_conf
from sanic import Blueprint
from appconfigsvr.auth.permission import permission_check, get_permission, PERMISSION

bp = Blueprint('salt_run_config', url_prefix='')
_logger = logging.getLogger(__name__)


@bp.get("/salt_run_config_list")
async def salt_run_config_list(request):
    try:
        app_name = request.raw_args.get("app_name", "")
        page = int(request.raw_args.get("page", 1))
        limit = int(request.raw_args.get("limit", 30))
        cur = get_app_config_collection().find({"app_name": {"$regex": app_name}},
                                               {"_id": 0, "app_name": 1, "execmd": 1, "misc": 1, "remark": 1})
        _count= cur.count()

        cur.skip((page - 1) * limit).limit(limit)
        res = []
        for doc in cur:
            if "misc" not in doc or not doc['misc']:
                doc['misc'] = [
                    ["filebeat", ""],
                ]
            res.append(doc)

        return response.json(
            {"code": 0, "message": "", "data": res, "count": _count})
    except Exception as e:
        _logger.exception("url %s" % request.url)
        return response.json({"code": 4003, "message": "error message %s" % e, "data": {}})


@bp.post('/salt_run_config')
async def add_salt_run_config(request):
    try:
        _json = request.json
        app_name = _json["app_name"]

        _logger.info("app_name %s  config %s host %s", app_name, request.host)
        get_app_config_collection().find_one_and_update({"app_name": app_name},
                                                              {"$set": _json},
                                                              upsert=True)

    except Exception as e:
        _logger.exception("url %s" % request.url)
        _logger.exception(e)
        return response.json({"code": 4003, "message": "error message %s" % e, "data": {}})
    else:
        return response.json({"code": 0, "message": "", "data": {}})
